package com.mindskip.xzs.controller.wx.student;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.controller.wx.BaseWXApiController;
import com.mindskip.xzs.domain.*;
import com.mindskip.xzs.domain.enums.ExamUserStatusEnum;
import com.mindskip.xzs.domain.enums.QuestionTypeEnum;
import com.mindskip.xzs.event.CalculateExamPaperAnswerCompleteEvent;
import com.mindskip.xzs.event.UserEvent;
import com.mindskip.xzs.exception.BusinessException;
import com.mindskip.xzs.repository.ExamMapper;
import com.mindskip.xzs.repository.NewUserMapper;
import com.mindskip.xzs.service.*;
import com.mindskip.xzs.utility.ExamUtil;
import com.mindskip.xzs.viewmodel.IdNameKV;
import com.mindskip.xzs.viewmodel.admin.exam.ExamPaperEditRequestVM;
import com.mindskip.xzs.viewmodel.student.exam.ExamPaperReadVM;
import com.mindskip.xzs.viewmodel.student.exam.ExamPaperSubmitItemVM;
import com.mindskip.xzs.viewmodel.student.exam.ExamPaperSubmitVM;
import com.mindskip.xzs.viewmodel.student.exampaper.ExamPaperAnswerPageVM;
import com.mindskip.xzs.viewmodel.student.exampaper.ExamPaperAnswerReq;
import com.mindskip.xzs.viewmodel.wx.student.answer.ExamPaperAnswerPageRes;
import com.mindskip.xzs.viewmodel.wx.student.answer.ExamPaperAnswerSearchPageRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;


@Controller("WXStudentExamPaperAnswerController")
@RequestMapping(value = "/api/wx/student/exampaper/answer")
@ResponseBody
public class ExamPaperAnswerController extends BaseWXApiController {

    private final ExamPaperAnswerService examPaperAnswerService;
    private final ApplicationEventPublisher eventPublisher;
    private final ExamPaperService examPaperService;
    @Resource
    private ExamUserService examUserService;
    @Resource
    private NewUserService newUserService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private ExamService examService;
    @Resource
    private NewExamPaperAnswerService newExamPaperAnswerService;
    @Resource
    private NewUserMapper newUserMapper;
    @Resource
    private ExamMapper examMapper;

    @Autowired
    public ExamPaperAnswerController(ExamPaperAnswerService examPaperAnswerService, ApplicationEventPublisher eventPublisher, ExamPaperService examPaperService) {
        this.examPaperAnswerService = examPaperAnswerService;
        this.eventPublisher = eventPublisher;
        this.examPaperService = examPaperService;
    }

    @RequestMapping(value = "/pageList", method = RequestMethod.POST)
    public RestResponse<PageInfo<ExamPaperAnswerPageRes>> pageList(@Valid ExamPaperAnswerPageVM model) {
        model.setCreateUser(getCurrentUser().getId());
        return RestResponse.ok(examPaperAnswerService.studentPage(model));
    }

    @RequestMapping(value = "/search/pageList", method = RequestMethod.POST)
    public RestResponse<PageInfo<ExamPaperAnswerSearchPageRes>> pageListSearch(@RequestBody ExamPaperAnswerReq req) {
        //req.setUserId(getCurrentUser().getId());
        return RestResponse.ok(examPaperAnswerService.studentPageSearch(req));
    }

    /**
     * 查询员工kv列表
     */
    @RequestMapping(value = "/search/employee", method = RequestMethod.GET)
    public RestResponse<List<IdNameKV>> selectEmployee(@RequestParam(required = false, value = "keyword") String keyword) {
        return RestResponse.ok(newUserService.queryUserKVListInCache(keyword));
    }

    /**
     * 查询部门kv列表
     */
    @RequestMapping(value = "/search/dept", method = RequestMethod.GET)
    public RestResponse<List<IdNameKV>> selectDept(@RequestParam(required = false, value = "keyword") String keyword) {
        return RestResponse.ok(departmentService.queryDeptKVListInCache(keyword));
    }

    /**
     * 查询有权限部门kv列表
     */
    @RequestMapping(value = "/rank/dept", method = RequestMethod.GET)
    public RestResponse<List<IdNameKV>> selectRankDept() {
        return RestResponse.ok(departmentService.queryUserDeptKV(getCurrentUser().getId()));
    }

    /**
     * 查询有权限部门kv列表
     */
    @RequestMapping(value = "/dept/user", method = RequestMethod.GET)
    public RestResponse<List<IdNameKV>> selectDeptUsers(
            @RequestParam(value = "deptId") Long deptId,
            @RequestParam(required = false, value = "keyword") String keyword) {
        return RestResponse.ok(newUserService.queryUserKVListForSearch(deptId, keyword));
    }

    @RequestMapping(value = "/answerSubmit", method = RequestMethod.POST)
    public RestResponse answerSubmit(HttpServletRequest request) {
        ExamPaperSubmitVM examPaperSubmitVM = requestToExamPaperSubmitVM(request);
        return submit(examPaperSubmitVM);
    }

    private RestResponse submit(ExamPaperSubmitVM examPaperSubmitVM) {
        User user = examPaperSubmitVM.getUser() == null ? getCurrentUser() : examPaperSubmitVM.getUser();

        ExamPaperAnswerInfo examPaperAnswerInfo = examPaperAnswerService.calculateExamPaperAnswer(examPaperSubmitVM, user);
        if (null == examPaperAnswerInfo) {
            return RestResponse.fail(2, "试卷不能重复做");
        }
        // 更新提交员工考试状态
        examUserService.updateUserExamStatus(examPaperSubmitVM.getExamId(), user.getId(), ExamUserStatusEnum.DONE.getCode());

        ExamPaperAnswer examPaperAnswer = examPaperAnswerInfo.getExamPaperAnswer();
        Integer userScore = examPaperAnswer.getUserScore();
        String scoreVm = ExamUtil.scoreToVM(userScore);

        /*
         * 自动生成答卷
         */
        Lock lock = new ReentrantLock(true);
        lock.lock(); // 进行加锁
        try {
            Exam exam = examMapper.selectOne(new LambdaQueryWrapper<Exam>().eq(Exam::getId, examPaperSubmitVM.getExamId()));
            if (exam == null) {
                throw new RuntimeException("提交考试不存在");
            }
            double passScore = exam.getPassScore() != null && exam.getPassScore() > 0 ? exam.getPassScore() : examPaperAnswer.getPaperScore() * 0.6;
            if (!exam.getAutoDone() && userScore >= passScore * 10) {
                exam.setAutoDone(true);
                examMapper.updateById(exam);
                autoSubmit(examPaperSubmitVM);
            }
        } finally {
            lock.unlock();// 释放锁
        }

        UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
        String content = user.getUserName() + " 提交试卷：" + examPaperAnswerInfo.getExamPaper().getName()
                + " 得分：" + scoreVm
                + " 耗时：" + ExamUtil.secondToVM(examPaperAnswer.getDoTime());
        userEventLog.setContent(content);
        eventPublisher.publishEvent(new CalculateExamPaperAnswerCompleteEvent(examPaperAnswerInfo));
        eventPublisher.publishEvent(new UserEvent(userEventLog));

        return RestResponse.ok(scoreVm);
    }


    /**
     * 特殊部门自动生成答卷
     */
    private void autoSubmit(ExamPaperSubmitVM examPaperSubmitVM) {
        List<IdNameKV> autoExamUsers = newUserMapper.selectAutoExamUsers(examPaperSubmitVM.getExamId());
        if (CollectionUtil.isNotEmpty(autoExamUsers)) {
            autoExamUsers.forEach(autoExamUser -> {
                examPaperSubmitVM.setUser(
                        new User()
                                .setId(Math.toIntExact(autoExamUser.getId()))
                                .setUserName(autoExamUser.getName())
                                .setRealName(autoExamUser.getName())
                );
                submit(examPaperSubmitVM);
            });
        }
    }


    private ExamPaperSubmitVM requestToExamPaperSubmitVM(HttpServletRequest request) {
        ExamPaperSubmitVM examPaperSubmitVM = new ExamPaperSubmitVM();
        examPaperSubmitVM.setId(Integer.parseInt(request.getParameter("id")));
        examPaperSubmitVM.setExamId(Integer.parseInt(request.getParameter("examId")));
        examPaperSubmitVM.setDoTime(Integer.parseInt(request.getParameter("doTime")));
        List<String> parameterNames = Collections.list(request.getParameterNames()).stream()
                .filter(n -> n.contains("_"))
                .collect(Collectors.toList());
        //题目答案按序号分组
        Map<String, List<String>> questionGroup = parameterNames.stream().collect(Collectors.groupingBy(p -> p.substring(0, p.indexOf("_"))));
        List<ExamPaperSubmitItemVM> answerItems = new ArrayList<>();
        questionGroup.forEach((k, v) -> {
            ExamPaperSubmitItemVM examPaperSubmitItemVM = new ExamPaperSubmitItemVM();
            String p = v.get(0);
            String[] keys = p.split("_");
            examPaperSubmitItemVM.setQuestionId(Integer.parseInt(keys[1]));
            examPaperSubmitItemVM.setItemOrder(Integer.parseInt(keys[0]));
            QuestionTypeEnum typeEnum = QuestionTypeEnum.fromCode(Integer.parseInt(keys[2]));
            if (v.size() == 1) {
                String content = request.getParameter(p);
                examPaperSubmitItemVM.setContent(content);
                if (typeEnum == QuestionTypeEnum.MultipleChoice) {
                    examPaperSubmitItemVM.setContentArray(Arrays.asList(content.split(",")));
                }
            } else {  //多个空 填空题
                List<String> answers = v.stream().sorted(Comparator.comparingInt(ExamUtil::lastNum)).map(inputKey -> request.getParameter(inputKey)).collect(Collectors.toList());
                examPaperSubmitItemVM.setContentArray(answers);
            }
            answerItems.add(examPaperSubmitItemVM);
        });
        examPaperSubmitVM.setAnswerItems(answerItems);
        return examPaperSubmitVM;
    }


    @PostMapping(value = "/read/{id}")
    public RestResponse<ExamPaperReadVM> read(@PathVariable Integer id) {
        ExamPaperReadVM vm = new ExamPaperReadVM();
        ExamPaperAnswer examPaperAnswer = newExamPaperAnswerService.getById(id);
        Exam exam = examService.getById(examPaperAnswer.getExamId());
        if (exam == null) {
            throw new BusinessException("该考试不存在");
        }
        ExamPaperEditRequestVM paper = examPaperService.examPaperToVM(examPaperAnswer.getExamPaperId());
        ExamPaperSubmitVM answer = examPaperAnswerService.examPaperAnswerToVM(examPaperAnswer.getId());
        vm.setPaper(paper);
        vm.setAnswer(answer);
        if (exam.getShowCorrectAnswer() != null) {
            vm.setShowCorrectAnswer(exam.getShowCorrectAnswer());
        }
        if (exam.getShowAnalysis() != null) {
            vm.setShowAnalysis(exam.getShowAnalysis());
        }
        return RestResponse.ok(vm);
    }
}
